<template>
  <div class="file_box">
    <!-- 文件上传 -->
    <div class="d-flex flex-wrap" v-if="type == 'file'">
      <div>
        <el-upload
          ref="upload"
          :show-file-list="false"
          class="upload-demo m-l10"
          :http-request="update"
          :on-remove="onRemove"
          :disabled="disabled"
          :on-exceed="onExceedHandel"
        >
          <template #trigger>
            <el-button
              :disabled="disabled"
              v-if="showButton"
              class="btn_class"
              style="color: #fc7018; border: 1px solid #fc7018"
              plain
              color="#fff8f6"
            >
              <svg-icon
                icon-class="project-detail-icon-l-shangchuan"
                class="icon"
              />
              上传文件</el-button
            >
          </template>
        </el-upload>
      </div>
      <div class="filesContent d-flex">
        <div class="files_c_item m-b10" v-for="(v, i) in files" :key="i">
          <el-icon
            color="#999999"
            v-if="!disabled"
            @click="handelFileDelete(v)"
            class="icon_delete"
          >

            <CircleCloseFilled />
          </el-icon>
          <span class="icon_name" @click="handelFileDown(v)"
            ><el-icon> <Document  /> </el-icon>{{ v.fileName }}</span
          >
        </div>
      </div>
    </div>

    <!-- 图片上传 -->
    <div class="d-flex" v-if="type == 'img'">
      <div class="d-flex filesContent_img" v-for="(v, i) in files" :key="i">
        <div
          class="files_c_item_img m-r20"
          @mouseenter="isShow[i] = true"
          @mouseleave="isShow[i] = false"
        >
          <el-icon class="icon_delete"  v-if="!disabled" @click.stop="handelFileDelete(v)"
            ><CircleCloseFilled
          /></el-icon>
          <el-icon
            v-show="isShow[i]"
            class="icon_preview"
            @click.stop="handlePictureCardPreview(v)"
            ><CirclePlus
          /></el-icon>

          <el-icon
            v-show="isShow[i]"
            class="icon_down"
            @click.stop="handelFileDown(v)"
            ><Download
          /></el-icon>
          <img :src="dialogImageUrl" alt="" />
        </div>
      </div>
      <div v-if="restrictionLimit != files.length">
        <el-upload
          ref="upload"
          :show-file-list="false"
          class="upload-img"
          :http-request="update"
          :on-preview="handlePictureCardPreview"
          list-type="picture-card"
          :disabled="disabled"
          :on-exceed="onExceedHandel"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </div>
    </div>
    <div v-if="restriction && showButton" class="restriction m-t10">
      限制上传数量: <span>{{ restrictionLimit }}</span>
    </div>
  </div>

  <el-dialog v-model="dialogVisible">
    <img style="width: 100%" w-full :src="dialogImageUrl" alt="图片预览" />
  </el-dialog>
</template>

<script setup>
import { ElUpload, ElLoading,ElRadio,ElRadioGroup, ElMessage,ElSelect,ElOption, ElIcon, ElDialog } from 'element-plus'
import { ref, watch } from 'vue'
import {
  Document,
  CircleCloseFilled,
  Plus,
  CirclePlus,
  Download
} from '@element-plus/icons-vue'
import { fileCallback } from '@/api/common.js'
import { fileControlApi } from '@/api/assets'
const props = defineProps({
  showButton:{
      type: Boolean,
      default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  /* 文件上传file 图片上传img */
  type: {
    type: String,
    default: 'file'
  },
  /* 上传参数 */
  /* 业务类型（1房源业务，2资产业务 11招标比选会审 12招标结果会审 13招标合同会审 14招标中标通知书 15招标合同扫描件） */
  businessType: {
    type: Number,
    default: 0
  },
  /* 关联编号id */
  associationId: {
    type: String,
    default: ''
  },

  files: {
    type: Array,
    default: []
  },
  /* 限制数量 */
  restriction: {
    type: Boolean,
    default: true
  },
  restrictionLimit: {
    type: Number,
    default: 99
  }
})

const emits = defineEmits(['updateFiles'])
const isShow = ref([])

// 下载
const handelFileDown = (item) => {
  let a = document.createElement('a')
  a.href = item.fileAddress
  a.download = item.fileName
  console.log(item)

  switch (item.fileName.split('.')[1]) {
    case 'pdf':
      a.target = '_blank'
      break
    case 'jpg':
      a.target = '_blank'
      break
    case 'bmp':
      a.target = '_blank'
      break
    case 'jpeg':
      a.target = '_blank'
      break
    case 'gif':
      a.target = '_blank'
      break
    case 'png':
      a.target = '_blank'
      break

    default:
      break
  }
  a.click(() => {
    return false
  })
  console.log(a.href);
  URL.revokeObjectURL(a.href)
  a.remove()
}
// 删除
const handelFileDelete = (item) => {
  let i =props.files.findIndex((v, i) => v.fileUrlKey != item.fileUrlKey)
  props.files.splice(i,1)
  ElMessage.success('删除成功!')
  emits('updateFiles', props.files)

}
const dialogImageUrl = ref('')
const onRemove = () => {

}
const dialogVisible = ref(false)
const handlePictureCardPreview = (e) => {
  console.log(e)
  dialogImageUrl.value = e.fileAddress
  dialogVisible.value = true
}

const update = (file) => {
  if (props.files.length == props.restrictionLimit) {
    ElMessage.warning('文件上传数量超限制!')
    return

  }

  //校验是否是图片
  if (props.type == 'img') {
    let types=['image/jpeg','image/png','image/gif','image/bmp','image/jpg']
    if(!types.includes(file.file.type)){
      ElMessage.warning('请上传图片!')
      return
    }

  }
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  let url = 'uploadImgFile'
  if (props.type === 'img') {
    url = 'uploadImgFile'
  } else {
    url = 'uploadDocumentFile'
  }

  let uploadFile = new FormData()
  uploadFile.append('file', file.file)
  uploadFile.append('associationId', props.associationId)
  uploadFile.append('businessType ', props.businessType)

  fileControlApi[url](uploadFile).then((res) => {
    if (res.code === '200') {

      loading.close()
      ElMessage.success('上传成功!')
      console.log(props.files);

      props.files.unshift({
        ...res.data
      })
      emits('updateFiles', props.files)
      if (props.type == 'img') {
        dialogImageUrl.value = res.data.fileAddress
      }
    }
  })
}

const onExceedHandel = () => {
  ElMessage.warning('文件上传数量超限制!')
}
</script>
<style lang="scss" scoped>
.filesContent {
  align-items: center;
  flex-wrap: wrap;
  .files_c_item {
    min-width: 120px;
    padding: 0 30px;
    position: relative;

    .icon_delete {
      position: absolute;
      top: -10px;
      right: 0;
      cursor: pointer;
    }
    .icon_delete:hover {
      color: red;
    }

    .icon_name {
      color: #999;
      cursor: pointer;
    }
    .icon_name:hover {
      color: #fc7018;
    }
  }
}

.restriction {
  font-size: 12px;
  font-family: SourceHanSansCN-Normal, SourceHanSansCN;
  color: #f12527;
}

.upload-img {
  position: relative;
  width: 67px;
  height: 67px;
  .el-icon {
    color: #fc7018;
  }

  :deep(.el-upload) {
    width: 100%;
    height: 100%;
    border: 1px solid #fc7018;
    background-color: #fff8f6;
  }
  .icon_delete {
    position: absolute;
    top: -10px;
    right: -10px;
    cursor: pointer;
  }
}

.filesContent_img {
  flex-wrap: wrap;
  .files_c_item_img {
    position: relative;
    width: 67px;
    height: 67px;
    border: 1px solid #fc7018;
    background-color: #fff8f6;
    border-radius: 5px;
    // cursor: pointer;
    text-align: center;
    line-height: 67px;
    img {
      position: absolute;
      width: 100%;
      z-index: 1;
      left: 0;
      top: 0;
      height: 100%;
      object-fit: cover;
    }
    .icon_delete {
      position: absolute;
      top: -8px;
      right: -8px;
      cursor: pointer;
      color: #fc7018;
      z-index: 3;
    }
    .icon_preview,
    .icon_down {
      cursor: pointer;
      color: #999;
      z-index: 3;
    }
    .icon_preview:hover,
    .icon_down:hover {
      color: #fc7018;
    }
  }
}

.file_box {
  min-height: 100px;
}
</style>
